<?php

/**
 * uniBoard ACP Inactive Users List
 *
 * Light and fast forum solution for web 2.0-like communities.
 *
 * @package		uniBoard
 * @author		Rafał Pitoń
 * @license		http://www.gnu.org/licenses/gpl-3.0.html
 * @since		Version 0.1
 * 
 * ------------------------------------------------------------------------
 * 
 * $Date: 2010-09-20 21:23:27 +0000 (Mon, 20 Sep 2010) $
 * $Revision: 64 $
 * $Author: rafio.xudb@gmail.com $
 */

// ------------------------------------------------------------------------

class action_inactive{
	
	/**
	 * Main class pointer
	 *
	 * @var object
	 */
	
	private $appCore		= NULL;
	
	/**
	 * Link Base
	 *
	 * @var string
	 */
	
	private $url_base		= 'act=inactive&st=%s';
	
	// ------------------------------------------------------------------------

	/**
	 * Initialise Action
	 *
	 * @param object $appCore
	 */
	
	function __construct( $appCore){
		
		// Store appCore pointer
		$this -> appCore = $appCore;
		
		// Load fields templates
		$appCore -> templates['form_inputs'] = new tpl_form_inputs( $appCore);
		
		// Do something?
		if ( strlen( $appCore -> _POST( 'do')) > 0)
		{
			// Perform Action
			$this -> doAction();
		}
		else
		{
			// Cache output
			ob_start();
			
			// Draw Results?
			$this -> doSearch();
			
			// Draw Search Form
			$this -> drawSearchForm();
			
			// Draw output
			$appCore -> output -> draw( $appCore -> lang['acp_users_inactvie'], array( $appCore -> adminLink( 'act=inactive') => $appCore -> lang['acp_users_inactvie']), ob_get_clean());
		}
		
	}
	
	function doAction(){
		
		// Try-Catch
		try
		{
			// Bad Action code?
			if ( $this -> appCore -> _POST( 'do') != 'delete' && $this -> appCore -> _POST( 'do') != 'mail' && $this -> appCore -> _POST( 'do') != 'activate')
			{
				throw new exc_small( $this -> appCore -> lang['wrong_action_code']);
			}
			
			// Grab selected users
			$users = $this -> appCore -> listInput( 'select_user');
			
			// Nothing selected?
			if ( empty( $users))
			{
				throw new exc_small( $this -> appCore -> lang['nothing_selected']);
			}
			
			// Users Names (we gonna put them into LOG)
			$users_names = array();
			
			// Whitelist users
			$users_wlist = array();
			
			// Select Users (no more than 15 in row)
			$this -> appCore -> db -> query( 'SELECT user_id, user_login, user_name, user_email, user_activation, user_code, user_groups, user_language
			FROM ' . DB_PREFIX . 'users
			WHERE user_activation > \'0\' AND user_id IN (' . join( ',', $users) . ')
			ORDER BY user_activation, user_language
			LIMIT 15');
			
			// Parse Result
			while ( $user_result = $this -> appCore -> db -> fetch_array())
			{
				// Explode user groups
				$user_result[6] = (array) explode( ',', $user_result[6]);
				
				// Are we going to delete admin?
				if ( in_array( 1, $user_result[6]) && $this -> appCore -> _POST( 'do') == 'delete')
				{
					// Stop Result
					$this -> appCore -> freeResult();
					
					// Throw exception
					throw new exc_small( $this -> appCore -> lang['acp_users_delete_admin']);
				}
				
				// Are we going to delete ourself?
				if ( $user_result[0] == $this -> appCore -> user['id'] && $this -> appCore -> _POST( 'do') == 'delete')
				{
					// Stop Result
					$this -> appCore -> freeResult();
					
					// Throw exception
					throw new exc_small( $this -> appCore -> lang['acp_users_delete_yourself']);
				}
				
				// Put name to log
				$users_names[$user_result[0]] = $user_result[2];
				
				// Make whitelist
				$users_wlist[] = array(
					'id' 				=> $user_result[0],
					'login' 			=> $user_result[1],
					'name' 				=> $user_result[2],
					'email' 			=> $user_result[3],
					'activation' 		=> $user_result[4],
					'code' 				=> $user_result[5],
					'groups' 			=> $user_result[6],
					'language' 			=> $user_result[7]
				);
			}
			
			// Found anything?
			if ( empty( $users_wlist))
			{
				throw new exc_small( $this -> appCore -> lang['acp_users_select_not_found']);
			}
			
			// Ignore user abort and keep running
			if ( function_exists( ' ignore_user_abort'))
			{
				 ignore_user_abort( true);	
			}
			
			// Set Log and redirect user
			switch ( $this -> appCore -> _POST( 'do'))
			{
				case 'activate':
					// Log
					$this -> appCore -> logAdmin( 'log_admin_activated_users', htmlspecialchars( join( ', ', $users_names)));
					
					// Redirect
					$this -> appCore -> output -> drawRedirect( $this -> appCore -> adminLink( 'act=inactive'), $this -> appCore -> lang['acp_users_inactive_activation_done']);
				break;
				
				case 'mail':
					// Log
					$this -> appCore -> logAdmin( 'log_admin_resended_activation_to_users', htmlspecialchars( join( ', ', $users_names)));
					
					// Redirect
					$this -> appCore -> output -> drawRedirect( $this -> appCore -> adminLink( 'act=inactive'), $this -> appCore -> lang['acp_users_inactive_send_done']);
				break;
				
				case 'delete':
					// Log
					$this -> appCore -> logAdmin( 'log_admin_deleted_users', htmlspecialchars( join( ', ', $users_names)));
					
					// Redirect
					$this -> appCore -> output -> drawRedirect( $this -> appCore -> adminLink( 'act=inactive'), $this -> appCore -> lang['acp_users_inactive_deleted_done']);
				break;
			}
			
			// Keep Script Alive
			$this -> appCore -> stayAlive();
			
			// Delete users?
			if ( $this -> appCore -> _POST( 'do') == 'delete')
			{
				// Just Nail selected users
				$this -> appCore -> users -> deleteUsers( $users_names);
			}
			else
			{
				// Garbage our ysers
				unset( $users_names);
				
				// Count users
				$users_l = count( $users_wlist);
				
				// Reiterate Users and activate them
				if ( $this -> appCore -> _POST( 'do') == 'activate')
				{
					// Update new users
					$update_new = array();
					
					// Group memberships (we move new users from 4 to 3)
					$groups_insert = array();
					
					// Update old users
					$update_old = array();
					
					for ( $i = 0; $i < $users_l; $i ++)
					{
						// User is old member?
						if ( $users_wlist[$i]['activation'] == 3)
						{
							// Update old member
							$update_old[] = $users_wlist[$i]['id'];
						}
						else
						{
							// Update new member
							$update_new[] = $users_wlist[$i]['id'];
							
							// Add new groups insert
							$groups_insert[] = '\'3\', \'' . $users_wlist[$i]['id'] . '\'';
						}
					}
										
					// Update new members?
					if ( !empty( $update_new))
					{
						// Set Their groups to registered
						$this -> appCore -> db -> update( array( 'group_id' => 3, 'user_groups' => 3, 'user_activation' => 0, 'user_code' => ''), 'users', 'user_id IN (' . join( ',', $update_new) . ')');
						
						// Prune their current memberships
						$this -> appCore -> db -> delete( 'user_groups_members', 'user_id IN (' . join( ',', $update_new) . ')');
						
						// Set their Memberships
						$this -> appCore -> db -> multipleInsert( 'group_id, user_id', $groups_insert, 'user_groups_members');
					}
					
					// Update old members?
					if ( !empty( $update_old))
					{
						// Turn off their activation requirement
						$this -> appCore -> db -> update( array( 'user_activation' => 0, 'user_code' => ''), 'users', 'user_id IN (' . join( ',', $update_old) . ')');
					}
					
					// Garbage out
					unset( $update_new);
					unset( $groups_insert);
					unset( $update_old);
				}
				
				// Current template file params
				$current_type = 0;
				$current_language = 0;
				
				//Current template file
				$current_template = '';
								
				// Start Mailer
				$mailer = new class_mailer( $this -> appCore, true);
				
				// Reiterate Users and send Mails
				for ( $i = 0; $i < $users_l; $i ++)
				{
					// Load template?
					if (($this -> appCore -> _POST( 'do') == 'mail' && $current_type != $users_wlist[$i]['activation']) || $current_language != $users_wlist[$i]['language'])
					{
						// Set New Data
						$current_type = $users_wlist[$i]['activation'];
						$current_language = $users_wlist[$i]['language'];
						
						// Load new template
						if ( $this -> appCore -> _POST( 'do') == 'activate')
						{
							$current_template = file_get_contents( CACHE_PATH . 'lang_' . $current_language . '/email_activated_adm.txt');
						}
						else
						{
							$current_template = file_get_contents( CACHE_PATH . 'lang_' . $current_language . '/email_activation_' . $current_type . '_adm.txt');
						}
					}
					
					// Send Email
					if ( $this -> appCore -> _POST( 'do') == 'activate')
					{
						// Send E-Mail
						$mailer -> sendEmail(
							$users_wlist[$i]['email'],
							$users_wlist[$i]['name'],
							$this -> appCore -> lang['email_register_title'],
							class_strings::parseMailText( $current_template, array(
								'{USER_NAME}' 						=> $users_wlist[$i]['name'],
								'{BOARD_NAME}' 						=> $this -> appCore -> conf['board_name'],
								'{BOARD_LOGIN_URL}' 				=> $this -> appCore -> emailLink( 'act=login', $this -> appCore -> lang['board_nav_login']),
								'{BOARD_URL}' 						=> $this -> appCore -> emailLink()
							)));
					}
					else
					{
						// Send E-Mail
						$mailer -> sendEmail(
							$users_wlist[$i]['email'],
							$users_wlist[$i]['name'],
							$this -> appCore -> lang['email_register_title'],
							class_strings::parseMailText( $current_template, array(
								'{USER_NAME}' 						=> $users_wlist[$i]['name'],
								'{USER_ACTIVATION_CODE}' 			=> $this -> api -> user_code,
								'{BOARD_NAME}' 						=> $this -> appCore -> conf['board_name'],
								'{BOARD_ACTIVATION_URL}' 			=> $this -> appCore -> emailLink( 'act=activate&user=' . $users_wlist[$i]['id'] . '&code=' . $users_wlist[$i]['code'], $this -> appCore -> lang['board_nav_activation']),
								'{BOARD_ACTIVATION_MANUAL_URL}' 	=> $this -> appCore -> emailLink( 'act=activate&user=' . $users_wlist[$i]['id'], $this -> appCore -> lang['board_nav_activation']),
								'{BOARD_URL}' 						=> $this -> appCore -> emailLink()
							)));
					}
					
					// Save Queue
					$mailer -> saveQueue();
				}
			}
		}
		catch ( exc_small $exception)
		{
			// Draw Error In redirection
			$this -> appCore -> output -> drawRedirect( $this -> appCore -> adminLink( 'act=inactive'), $exception -> message);
		}
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Searchs inactive users
	 *
	 */
	
	function doSearch(){
		
		// Try-Catch
		try
		{
			// Set Empty search SQL
			$search_sql = 'u.user_id > \'0\' AND u.user_activation > \'0\'';
			
			// Find in Login?
			if ( strlen( $this -> appCore -> _REQ( 'flogin')) > 0)
			{
				// Put in SQL
				$search_sql .= ' AND u.user_login LIKE \'' . str_replace( '*', '%', $this -> appCore -> db -> strEscape($this -> appCore -> _REQ( 'flogin'), true)) . '\'';
				
				// Put in URL
				$this -> url_base .= '&flogin=' . class_strings::sprintfEnc( $this -> appCore -> _REQ( 'flogin'));
			}
			
			// Find in Name?
			if ( strlen( $this -> appCore -> _REQ( 'fname')) > 0)
			{
				// Put in SQL
				$search_sql .= ' AND u.user_name LIKE \'' . str_replace( '*', '%', $this -> appCore -> db -> strEscape($this -> appCore -> _REQ( 'fname'), true)) . '\'';
				
				// Put in URL
				$this -> url_base .= '&fname=' . class_strings::sprintfEnc( $this -> appCore -> _REQ( 'fname'));
			}
			
			// Find in Login?
			if ( strlen( $this -> appCore -> _REQ( 'fmail')) > 0)
			{
				// Put in SQL
				$search_sql .= ' AND u.user_email LIKE \'' . str_replace( '*', '%', $this -> appCore -> db -> strEscape($this -> appCore -> _REQ( 'fmail'), true)) . '\'';
				
				// Put in URL
				$this -> url_base .= '&fmail=' . class_strings::sprintfEnc( $this -> appCore -> _REQ( 'fmail'));
			}
			
			// Find in Activation in GET?
			if ( strlen( $this -> appCore -> _GET( 'fact')) > 0)
			{
				// Put in SQL
				$search_sql .= ' AND u.user_activation IN (' . class_strings::stripBrackets( $this -> appCore -> db -> strEscape($this -> appCore -> _REQ( 'fact'))) . ')';
				
				// Put in URL
				$this -> url_base .= '&fact=' . class_strings::sprintfEnc( $this -> appCore -> _GET( 'fact'));
			}
			else if ( count( $this -> appCore -> listInput( 'fact')) > 0)
			{
				// Put in SQL
				$search_sql .= ' AND u.user_activation IN (' . join( ',', $this -> appCore -> listInput( 'fact')) . ')';
				
				// Put in URL
				$this -> url_base .= '&fact=' . class_strings::sprintfEnc( join( ',', $this -> appCore -> listInput( 'fact')));
			}
			
			// Nothing to Search?
			if ( !isset( $search_sql[0]))
			{
				throw new exc_small( $this -> appCore -> lang['acp_users_search_empty'], $this -> appCore -> lang['acp_users_inactvie']);	
			}
			
			// Count Users to display
			$users_num = $this -> appCore -> db -> count( 'users u', $search_sql);
			
			// Nothing found?
			if ( $users_num == 0)
			{
				throw new exc_small( $this -> appCore -> lang['acp_users_search_nothing'], $this -> appCore -> lang['acp_users_inactvie']);	
			}
			
			// Action Sure?
			$this -> appCore -> output -> js_code .= '
$(document).ready( function(){
	$(\'.form_button_inline\').click( function(){		
		if ( $(\'#do\').val() == "delete")
		{
			var user_page = confirm( "' . htmlspecialchars( $this -> appCore -> lang['delete_selected_items_sure']) . '");
			return user_page;
		}
	});
});
';
			
			// Make paginator
			$paginator = new class_paginator( $this -> appCore, $this -> appCore -> adminLink( $this -> url_base), $users_num, 15);
			
			// Draw Paginator
			echo $paginator -> draw();
			
			// Open table block
			echo $this -> appCore -> output -> openTableBlock( $this -> appCore -> lang['acp_found_users_form'] . $this -> appCore -> number( $users_num));
			echo $this -> appCore -> output -> openForm( $this -> appCore -> adminLink( 'act=inactive'));
			
			// Draw header
			echo $this -> appCore -> output -> tableHeader( array(
				array(
					'left_float width_icon',
					''
				),
				array(
					'left_float width_medium',
					$this -> appCore -> lang['column_user']
				),
				array(
					'right_float width_tiny center',
					$this -> appCore -> drawCheckbox( '', false, 'checkbox_master')
				),
				array(
					'right_float width_big',
					$this -> appCore -> lang['acp_users_list_activation']
				)
			));
				
			// Select Users
			$this -> appCore -> db -> query( 'SELECT u.user_id, u.user_login, u.user_name, u.user_email, u.user_activation, u.user_avatar_type, u.user_avatar_image, u.user_avatar_width, u.user_avatar_height, g.group_name, g.group_prefix, g.group_suffix
			FROM ' . DB_PREFIX . 'users u
			LEFT JOIN ' . DB_PREFIX . 'user_groups g ON  u.group_id = g.group_id
			WHERE ' . $search_sql . '
			ORDER BY u.user_name
			LIMIT ' . $paginator -> getPosition() . ',15');
			
			// Parse result
			while ( $user_result = $this -> appCore -> db -> fetch_assoc())
			{				
				// Draw row
				echo $this -> appCore -> output -> tableRow('<table>
		<tr>
			<td class="cell_pad width_icon">
				' . ( $user_result['user_avatar_type'] > 0 ? '<img src="' . class_users::avatarLocation($user_result['user_avatar_type']) . htmlspecialchars($user_result['user_avatar_image']) . '" alt="' . htmlspecialchars( $this -> appCore -> lang['user_avatar']) . '" title="' . htmlspecialchars( $this -> appCore -> lang['user_avatar']) . '" ' . $this -> appCore -> scaleImage( $user_result['user_avatar_width'], $user_result['user_avatar_height'], 32, 32, false) . ' />' : $this -> appCore -> output -> drawImage( 'user_noimage', $this -> appCore -> lang['user_no_avatar'])) . '
			</td>
			<td class="cell_pad left_border">
				<a href="' . $this -> appCore -> niceLink( 'act=user&user=' . $user_result['user_id'], $user_result['user_name']) . '"><b>' . $user_result['group_prefix'] . $user_result['user_name'] . $user_result['group_suffix'] . '</b></a> <b class="item_append">' . htmlspecialchars( $user_result['user_login']) . '</b>
				<div class="item_description">' . htmlspecialchars( $user_result['user_email']) . '</div>
			</td>
			<td class="cell_pad left_border width_big">
				' . $this -> appCore -> lang['acp_activation_' . $user_result['user_activation']] . '
			</td>
			<td class="cell_pad left_border width_tiny center">
				' . $this -> appCore -> drawCheckbox( 'select_user[' . $user_result['user_id'] . ']', false, 'checkbox_children') . '
			</td>
		</tr>
	</table>');
			}
			
			// Free result
			$this -> appCore -> db -> freeResult();
			
			// Draw Tools Row
			echo $this -> appCore -> output -> submitRow( '<div class="right_float">
				' . $this -> appCore -> drawList( 'do', array( 'activate' => $this -> appCore -> lang['acp_inactive_users_op_activate'], 'mail' => $this -> appCore -> lang['acp_inactive_users_op_code'], 'delete' => $this -> appCore -> lang['acp_inactive_users_op_delete'])) . ' ' . $this -> appCore -> drawButton( '', $this -> appCore -> lang['go'], 'form_button_inline') . '
			</div>');
			
			// Close Form
			echo $this -> appCore -> output -> closeForm();
			echo $this -> appCore -> output -> closeTableBlock();
			
			// Draw Paginator
			echo $paginator -> draw();
		}
		catch ( exc_small $exception)
		{
			// Draw Error
			$this -> appCore -> output -> error( $exception -> message, $exception -> title);
		}
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Draw Search Form
	 *
	 */
	
	function drawSearchForm(){
		
		// Open Form
		echo $this -> appCore -> output -> openFormBlock( $this -> appCore -> lang['acp_search_users_form'], $this -> appCore -> lang['acp_search_users_form_expl']);
		echo $this -> appCore -> output -> openForm( $this -> appCore -> adminLink( 'act=inactive&search=1'));
		
		// Draw Fields
		echo $this -> appCore -> output -> formItem( $this -> appCore -> lang['acp_search_users_find_login'], $this -> appCore -> drawTextInput( 'flogin', $this -> appCore -> _REQ( 'flogin')));
		echo $this -> appCore -> output -> formItem( $this -> appCore -> lang['acp_search_users_find_name'], $this -> appCore -> drawTextInput( 'fname', $this -> appCore -> _REQ( 'fname')));
		echo $this -> appCore -> output -> formItem( $this -> appCore -> lang['acp_search_users_find_email'], $this -> appCore -> drawTextInput( 'fmail', $this -> appCore -> _REQ( 'fmail')));
		echo $this -> appCore -> output -> formItem( $this -> appCore -> lang['acp_search_users_find_active'], $this-> appCore -> drawMultiList( 'fact', array(
			1 => $this -> appCore -> lang['acp_search_users_find_active_1'],
			2 => $this -> appCore -> lang['acp_search_users_find_active_2']
		), ( strlen( $this -> appCore -> _GET( 'fact')) > 0 ? explode( ',', $this -> appCore -> _GET( 'fact')) : $this -> appCore -> listInput( 'fact'))));
		
		// Close Block
		echo $this -> appCore -> output -> submitButton( $this -> appCore -> lang['send']);
		echo $this -> appCore -> output -> closeForm();
		echo $this -> appCore -> output -> closeFormBlock();
		
	}
	
}